package com.ljyh.cygnus.screens.viewmodel

import com.ljyh.cygnus.model.CommandUiState
import com.ljyh.cygnus.utils.PolicyManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

@HiltViewModel
class WLANViewModel @Inject constructor() : BaseViewModel() {

    private val _uiState = MutableStateFlow<CommandUiState>(CommandUiState.Idle)
    val uiState: StateFlow<CommandUiState> = _uiState.asStateFlow()


    /**
     * 禁用
     */
    fun disableWifi() {
        executeRootCommands(
            _uiState,
            "svc wifi disable",
            "iptables -D OUTPUT -o wlan0 -j DROP || true",
            "iptables -A OUTPUT -o wlan0 -j DROP",
            "iptables -D INPUT -i wlan0 -j DROP || true",
            "iptables -A INPUT -i wlan0 -j DROP"

        )
    }

    /**
     * 不管控
     */
    fun enableWifi() {

        executeRootCommands(
            _uiState,
            "svc wifi enable",
            // 使用-D删除规则，确保网络畅通
            "iptables -D OUTPUT -o wlan0 -j DROP || true",
            "iptables -D INPUT -i wlan0 -j DROP || true",
            "iptables -D OUTPUT -o p2p0 -j DROP || true"
        )
    }

    /**
     * 仅扫描
     */
    fun restrictionWifi() {
        executeRootCommands(
            _uiState,
            // 1. 必须先确保Wi-Fi是开启的，否则无法扫描
            "svc wifi enable",

            // 2. 清理旧规则，以防重复添加
            "iptables -D OUTPUT -o wlan0 -j DROP || true",
            "iptables -D OUTPUT -o p2p0 -j DROP || true",

            // 3. 使用 -I 将规则插入到OUTPUT链的【最顶端】(位置1)
            // 这确保了我们的阻止规则最先被匹配
            "iptables -I OUTPUT 1 -o wlan0 -j DROP",
            "iptables -I OUTPUT 1 -o p2p0 -j DROP"
        )
    }

    fun resetState() {
        _uiState.value = CommandUiState.Idle
    }
}
